﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MsForgeReboot.Framework.Entities;
using MsForgeReboot.Framework.Interfaces;

namespace MsForgeReboot.Services {
    public class UserService  : IUserService {

        private readonly MsForgeContext _context;

        public UserService(MsForgeContext ctx) {
            this._context = ctx;
        }


        #region IUserService Members

        public IList<User> GetUsers() {
            return this._context.Users.ToList();
        }

        public string[] GetUsernames(string ids, string separator = ",") {
            int[] uIDs = ids.Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries).Select(s => Int32.Parse(s)).ToArray();

            return this._context.Users.Where(u => uIDs.Contains(u.Id)).Select(u => u.Username).ToArray();
           
        }

        public User GetSingleUser(int id) {
            return this._context.Users.Single(s => s.Id == id);
        }

        public User GetSingleUser(string username) {
            return this._context.Users.Single(s => s.Username == username);
        }

        public void SaveOrEdit(int id, string userName, string publicName = null, bool? notifications = null) {
            var dbUser = this._context.Users.Single(s => s.Id == id);
            dbUser.Username = userName;
            dbUser.ReceiveNotifications = notifications ?? dbUser.ReceiveNotifications;
            dbUser.PublicName = publicName ?? dbUser.PublicName;
            
            this._context.SaveChanges();
        }

        public void DeleteUser(int id) {
            this._context.Users.Remove(this._context.Users.Single(s => s.Id == id));
            this._context.SaveChanges();
        }

        public IList<User> SearchTopTenUsers(string searchTerm) {
            return
                this._context.Users.Where(u => u.PublicName.Contains(searchTerm) || u.Username.Contains(searchTerm))
                    .Take(10)
                    .ToList();
        }

        public IList<User> FilterUsersByUsername(string username) {
            return this._context.Users.Where(u => u.Username.Contains(username)).ToList();
        }

        #endregion
    }
}
